/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logic.facade;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import logic.service.ProjectService;
import vo.IValueObject;
import vo.ProjectVO;
import vo.SubjectVO;

/**
 *
 * @author zergio
 */
public class ProjectFacade extends Facade {
    
    public ProjectFacade() {
        setService(new ProjectService());
    }

    @Override
    protected boolean exist(IValueObject vo) {
        return !(super.find(((ProjectVO) vo).getId()) == null);
    }

    public List<ProjectVO> getProjectsByCalendar(int id) {
        EntityManagerFactory emf = null;
        EntityManager em = null;
        List<ProjectVO> list = null;
        try{
            emf = Persistence.createEntityManagerFactory("StunnicusPU");
            em = emf.createEntityManager();
            list = (List<ProjectVO>) ((ProjectService)getService()).getProjectsByCalendar(id, em);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            if(em != null){
                em.clear();
                em.close();
            }
            return list;
        }
    }

    public void createProjectsFromSubjects(List<SubjectVO> subjects) {
        EntityManagerFactory emf = null;
        EntityManager em = null;
        EntityTransaction tx = null;
        try{
            emf = Persistence.createEntityManagerFactory("StunnicusPU");
            em = emf.createEntityManager();
            tx = em.getTransaction();
            tx.begin();
            ((ProjectService)getService()).createProjectsFromSubjects(subjects, em);
            tx.commit();
        }
        catch(Exception e){
            e.printStackTrace();
            if (em != null && tx != null) {
                tx.rollback();
            }
        }
        finally{
            if(em != null){
                em.clear();
                em.close();
            }
        }
    }
    
}
